import { Form, Input, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';

const { Option, OptGroup } = Select;

const templateType = {
  docx: 1,
  pptx: 3,
  xlsx: 2,
};

const docType = {
  docx: 'Word',
  pptx: 'PPT',
  xlsx: 'Excel',
};

const NewDocModal = ({ type, visible, onCreate, onCancel, dispatch }) => {
  const [form] = Form.useForm();

  const [templates, setTemplates] = useState([]);

  useEffect(() => {
    dispatch({
      type: 'templates/fetch',
      payload: { type: templateType[type] },
      callback: (res) => {
        setTemplates(res.data || []);
      },
    });
  }, []);

  return (
    <Modal
      visible={visible}
      title={`新建 ${docType[type]} 文档`}
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      width={1024}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="tid"
          label="模板"
          rules={[
            {
              required: true,
              message: '请选择文档模板!',
            },
          ]}
        >
          <Select style={{ width: '100%' }}>
            {templates.map((cat) => (
              <OptGroup key={cat.cid} label={cat.name}>
                {cat.templates.map((template) => (
                  <Option key={template.tid} value={template.tid}>
                    {template.title}
                  </Option>
                ))}
              </OptGroup>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="name"
          label="文档名称"
          rules={[
            {
              required: true,
              message: '请输入文档名称!',
            },
          ]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default connect(({ templates, loading }) => ({
  templates,
  fetching: loading.effects['templates/fetch'],
}))(NewDocModal);
